#include <iostream>
#include <vector>
#include <string>

using namespace std;

vector<string> fullJustify(vector<string>& words, int maxWidth) {
    int pre = 0, i = 0, sizet = 0, size; vector<string> ret;
    while(i < words.size()){
        // 获取一行不超过maxWidth长度的元素
        while(i != words.size() && sizet <= maxWidth + 1){
            sizet += words[i++].size()+1;
        }
        size = sizet-words[--i].size()-2, i = (i == words.size()-1 && sizet <= maxWidth+1) ? i : i-1; int blankNum;
        // 获取空格的最小长度以及剩余空格数
        if(i == pre){
            blankNum = maxWidth-size;
        }else{
            // blankNum = (maxWidth-size)%(i-pre) == 0 ? (maxWidth-size)/(i-pre) : (maxWidth-size)/(i-pre)+1;
            blankNum = (maxWidth-size)/(i-pre);
        }
        string temp, blank(blankNum+1, ' ');
        int last = i != pre ? (maxWidth-size)%(i-pre) : 0;
        // 合成一行，加入空格
        if(i == words.size()-1){
            for(int j = pre; j < i; j++){
                temp += words[j] + ' ';
            }
        }else{
            for(int j = pre; j < i; j++){
                temp += words[j] + blank;
                if(last-- > 0) temp += ' ';
            }
        }
        if(i == pre){
            string spblank(maxWidth-words[i].size(), ' ');
            temp = words[i] + spblank;
        }else if(i == words.size()-1){
            temp += words[i];
            string blank(maxWidth-temp.size(), ' ');
            temp += blank;
        }else{
            temp = temp.substr(0, temp.size()-(blankNum*(i-pre)-(maxWidth-size))) + words[i];
        }
        // 加入vector
        ret.push_back(temp);
        sizet = 0, i++, pre = i;
    }
    return ret;
}

int main(){
    vector<string> words = {"ask","not","what","your","country","can","do","for","you","ask","what","you","can","do","for","your","country"}; int maxWidth = 16;
    for(string s : fullJustify(words, maxWidth)){
        cout << s << endl;
    }
    return 0;
}
